package br.com.caim.viewcontroller.login;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.caim.bo.entidade.Usuario;
import br.com.caim.email.dao.Persistencia;
import br.com.caim.email.excecoes.negocio.NenhumaContaEncontrada;
import br.com.caim.viewcontroller.ActionPadrao;

public class LoginAction extends ActionPadrao {
	
	public ActionForward login(ActionMapping mapping, ActionForm genericForm, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NenhumaContaEncontrada {
		Persistencia persist = new Persistencia();
		LoginActionForm form = (LoginActionForm) genericForm;
		ActionForward fwd = mapping.findForward("fwTelaPrincipal");
		
		String login = form.getLogin();
		String senha = form.getSenha();
		
		Usuario user = new Usuario();
		user.setLogin(login);
		user.setSenha(senha);
		
		try {
			user = persist.pesquisarUsuario(user);
		} catch (Exception e) {
			e.printStackTrace();
			request.getSession().setAttribute("isLoginIncorreto", true);
			fwd = mapping.findForward("fwTelaLoginIncorreto");
			
			return fwd;
		}
		
		if(user == null) {
			fwd = mapping.findForward("fwTelaLoginIncorreto");
			
			return fwd;
		} else {
			Collection contas = persist.pesquisarContasUsuario(user.getId().toString());
			
			request.getSession().setAttribute("usuario", user);
			request.getSession().setAttribute("contas", contas);
			request.getSession().setAttribute("quantidadeContas", contas.size());
		}
		
		return fwd;
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm genericForm, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		
		return mapping.findForward("fwTelaLogin");
	}
}
